//设备型号库脚本定义
define(['knockout', 'platform.common', 'bootbox', 'knockout-bsTable', 'knockout-component', 'bootstrapValidator', 'bootstrapValidator-zhCN', 'sco.msg'], function (ko, platform) {
    var bootbox = require('bootbox');
    var rest = {
        get: function (id) {
            var param = {};
            param.model_id = id;
            return platform.servicebreak('/rest/modelLib/selectOne', param).responseJSON;
        }, remove: function (id) {//删除操作
            var param = {};
            param.model_id = id;
            platform.servicebreakAsync('~/rest/modelLib/delete', param, 'post')
                .done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        platform.showOperTip('DELSUC');
                        viewModel.tableViewModel.refresh();
                    } else {
                        platform.showErrorTip(response.meta.message);
                    }
                });
        }, save: function (param) {
            platform.servicebreakAsync('~/rest/modelLib/save', param, 'post',
                function () {
                    platform.showOperTip('dealing');
                }).done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('savesuc');
                    viewModel.tableViewModel.refresh();
                }
            });
        }
    };
    var deviceType = platform.getPubCode('fa9f865d-3fb6-4cec-a20f-cecee33a8980').responseObject;
    var kbTable = require('knockout-bsTable');

    var ViewModel = function () {
        var self = this;
        self.fixedModelType = ko.observable();
        self.deviceOpts = ko.computed(function () {
            return deviceType;
        });
        self.columns = [{checkbox: true, align: 'center', width: 30}, {
            field: 'display_order', title: '序号',
            formatter: function (value, row, index) {
                var options = self.tableViewModel.getOptions();
                var indexPageNum = parseInt(options.pageNumber);
                var indexPageSize = parseInt(options.pageSize);
                return ((indexPageNum - 1) * indexPageSize)
                    + (index + 1);
            },
            width: 35, align: 'center'
        }, {
            field: 'model_id', title: '型号标识', width: 120, visible: false
        }, {field: 'model_no', title: '型号', align: 'left', width: 180}, {
            field: 'resistance_value', title: '电阻值(Ω)', align: 'right', width: 120
        }, {
            field: 'reactance_value', title: '电抗值(F)', align: 'right', width: 120
        }, {field: 'power_value', title: '功率(W)', align: 'right', width: 120}, {
            field: 'model_type', title: '类型', formatter: function (value, row, index) {
                var showText;
                $.each(deviceType, function (index, node) {
                    if (node.code_value === value) {
                        showText = node.code_text;
                    }
                });
                return showText;
            }
        }];
        self.tableViewModel = new kbTable.bootstrapTableViewModel({
            autoHeight: true,
            url: platform.mapUrl('~/rest/modelLib/list'),
            toolbar: '#toolbar',
            queryParams: function (params) {
                return {
                    pageNumber: params.offset / params.limit + 1,
                    pageSize: params.limit,
                    model_type: self.fixedModelType()
                };
            },
            columns: self.columns
        });
        self.modelVisible = ko.observable(false);
        self.libViewModel = {
            enabled: ko.observable(true),
            title: ko.observable(),
            modelId: ko.observable(),
            modelNo: ko.observable(),
            resistanceValue: ko.observable(),
            reactanceValue: ko.observable(),
            powerValue: ko.observable(),
            modelType: ko.observable(),
            editStatus: ko.observable(),
            recordStatus: ko.observable(),
            deviceOpts: ko.computed(function () {
                return deviceType;
            }),
            resetForm: function () {//表单重置
                $('#detailForm').resetForm();
                if ($('#detailForm').data('bootstrapValidator') != null ||
                    $('#detailForm').data('bootstrapValidator') != undefined) {
                    $('#detailForm').data('bootstrapValidator').resetForm();
                }
                this.modelId('');
                this.modelNo('');
                this.resistanceValue(0);
                this.reactanceValue(0);
                this.powerValue(0);
                this.modelType('');
                this.recordStatus('');
                this.editStatus('');
                this.enabled(true);
            }, disableForm: function () {//表单内控件禁用
                $('#detailForm').find('input,textarea,select').attr('disabled', true);
            }, enableForm: function () {//表单内控件启用
                $('#detailForm').find('input,textarea,select').attr('disabled', false);
            }, setFormData: function (modelId) {//设置表单数据
                var result = rest.get(modelId);
                if (result instanceof Object && result.meta.success) {
                    var info = result.responseObject;
                    this.modelId(info.model_id);
                    this.modelNo(info.model_no);
                    this.resistanceValue(info.resistance_value);
                    this.reactanceValue(info.reactance_value);
                    this.powerValue(info.power_value);
                    this.modelType(info.model_type);
                }
            }, validateForm: function () {//表单验证
                $('#detailForm').bootstrapValidator({
                    message: 'This value is not valid',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    excluded: [':disabled'],
                    fields: {
                        modelNo: {
                            validators: {
                                notEmpty: {
                                    message: '*设备型号为必填字段,不可为空!'
                                }, stringLength: {
                                    min: 1,
                                    max: 50,
                                    message: '设备型号最多不超出50个字符!'
                                }
                            }
                        }
                    }
                });
            }, showNewForm: function () {//打开新表单
                this.resetForm();
                this.validateForm();
                this.enableForm();

                this.title('新增设备型号参数');
                this.modelId(platform.uuid());
                this.editStatus('0');
                this.recordStatus('1');
                self.modelVisible(true);
            }, showEditForm: function (modelId) {//打开编辑页面
                this.resetForm();
                this.validateForm();
                this.enableForm();
                this.title('编辑设备型号参数');
                this.setFormData(modelId);
                self.modelVisible(true);
            }, showViewForm: function (modelId) {//打开查询页面
                this.resetForm();
                this.disableForm();
                this.title('查看设备型号参数');
                this.setFormData(modelId);
                this.enabled(false);
                self.modelVisible(true);
            }, save: function () {//表单保存
                $('#detailForm').data('bootstrapValidator').validate();
                if (!$('#detailForm').data('bootstrapValidator').isValid()) {
                    platform.showOperTip('VALIDATEFAIL');
                    return;
                }

                var param = {};
                param.model_id = this.modelId();
                param.model_no = this.modelNo();
                param.reactance_value = this.reactanceValue();
                param.resistance_value = this.resistanceValue();
                param.power_value = this.powerValue();
                param.model_type = this.modelType();

                rest.save(param);
            }, close: function () {//表单关闭
                self.modelVisible(false);
                $('#libDetailViewDialog').toggleClass('hide');
            }
        };
        /**
         * 方法定义
         */
        self.fnAdd = function () {
            self.libViewModel.showNewForm();
            $('#libDetailViewDialog').toggleClass('hide');
        };
        self.fnEdit = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                var id = selections[0].model_id;
                self.libViewModel.showEditForm(id);
                $('#libDetailViewDialog').toggleClass('hide');
            } else {
                platform.showTip('edit');
            }
        };
        self.fnView = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                var id = selections[0].model_id;
                self.libViewModel.showViewForm(id);
                $('#libDetailViewDialog').toggleClass('hide');
            } else {
                platform.showTip('VIEW');
            }
        };
        self.fnRemove = function () {
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                bootbox.confirm({
                    title: '<i class="fa fa-warning"></i>&nbsp;&nbsp;删除提示信息',
                    size: 'small',
                    message: '当删除型号参数时，与之关联的数据将无法进行计算，确认是否删除?',
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success btn-sm'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default btn-sm'
                        }
                    },
                    callback: function (response) {
                        if (response) {
                            var id = selections[0].model_id;
                            rest.remove(id);
                        }

                    }
                });
            } else {
                platform.showTip('remove');
            }
        };
        self.fnImport = function () {//导入数据
        };
        self.fnSearch = function () {//列表页面查询
            var param = {};
            param.model_type = self.fixedModelType();
            self.tableViewModel.refresh(param);
        }
    };

    var viewModel = new ViewModel();

    return viewModel;
});